<?php
namespace app\admin\controller;
use app\service\apiService;
use app\service\billService;
use app\service\communityService;
use app\service\roominfoService;
use app\service\xcxService;
use think\facade\Db;
use think\facade\View;
use think\facade\Log;

ini_set('max_execution_time','0');
class Roominfo extends Common{
    public function billAdd(){
        $com = $this->pidTokenId();
        if(request()->isPost()){
           
            $data=request()->post();
            $roominfo = Db::table("roominfo")->where("id",$data["id"])->find();
           
            $bill['bill_entry_id'] = date('YmdHis', time()).\util\Tool::getRandomStr(6);
            $bill['community_id'] = $roominfo['community_id'];
            $bill['room_address'] = $roominfo['group']."-".$roominfo['building']."-".$roominfo['unit']."-".$roominfo['room'];
            
            $bill['out_room_id'] =  $roominfo['out_room_id'];
            $bill['cost_type'] = $data['cost_type'];
            $bill['bill_entry_amount'] = $data['price']*$roominfo["area"];
            $bill['acct_period'] = $data['acct_period'];
            $bill['release_day'] = $data['release_day'];
            $bill['deadline'] = $data['deadline'];
            $bill['out_trade_no'] = date('YmdHis').rand(100000,999999);
            $bill['status'] = 'WAIT_PAYMENT';
            $bill['time'] = date('Y-m-d H:i:s',time());
            $result = (new billService())->billAdd($bill);
            
            if(!empty($result)){
                return "添加账单成功";
            }else{
                return "添加账单失败";
            }
            //$this->success('添加账单成功',url('bill/billList'));
            
        }else{
            $roomid=request()->get("id");
            $roominfo=Db::table("roominfo")->where("id",$roomid)->find();
            $community=Db::table("community")->where("community_id",$roominfo["community_id"])->find();
            
            $roominfo["community_name"]=$community["community_name"];
            //查询费用类型
            $type=Db::table("costtype")->where("property_id",$community["property_id"])->select()->toArray();
           
            View::assign("roominfo",$roominfo);
            View::assign("type",$type);
            return View::fetch("bill_add");
        }
        
    }
    public function billAdd2(){
        $com = $this->pidTokenId();
        if(request()->isPost()){
            echo "<pre>";
            
            $data=request()->post();
            foreach($data["cost_type"] as $key=>$value){
                $bill['bill_entry_id'] = date('YmdHis', time()).\util\Tool::getRandomStr(6);
                $bill['community_id'] = $data['community_id'];
                $bill['room_address'] = $data['group']."-".$data['building']."-".$data['unit']."-".$data['room'];
                $roomlist = (new billService())->roomAddress($bill['community_id'],$bill['room_address']);
                $bill['out_room_id'] =  $data['out_room_id'];
                $bill['cost_type'] = $data['cost_type'][$key];
                $bill['bill_entry_amount'] = $data['bill_amount'][$key];
                $bill['acct_period'] = $data['acct_period'][$key];
                $bill['release_day'] = $data['release_day'][$key];
                $bill['deadline'] = $data['deadline'][$key];
                $bill['out_trade_no'] = date('YmdHis').rand(100000,999999);
                $bill['status'] = 'WAIT_PAYMENT';
                $bill['time'] = date('Y-m-d H:i:s',time());
                $result = (new billService())->billAdd($bill);
            }
            
            $this->success('添加账单成功',url('bill/billList'));
            
        }else{
            $roomid=request()->get("id");
            $roominfo=Db::table("roominfo")->where("id",$roomid)->find();
            var_dump($roominfo);die;
            $community=Db::table("community")->where("community_id",$roominfo["community_id"])->find();
            
            $roominfo["community_name"]=$community["community_name"];
            //查询费用类型
            $type=Db::table("costtype")->where("property_id",$community["property_id"])->select()->toArray();
            View::assign("roominfo",$roominfo);
            View::assign("type",$type);
            return View::fetch("bill_add");
        }
        
    }
    //下拉菜单
    public function fetchdata() {
        $type = request()->post('type');
        switch($type) {
            case 1:
                $community_id = request()->post('community_id');
                $group = array_unique((new roominfoService())->groupList($community_id));
                $group = array_filter($group);
                return array_values($group);
            case 2:
                $community_id = request()->post('community_id');
                $group = request()->post('group');
                $building = array_unique((new roominfoService())->buildingList($community_id,$group));
                sort($building);
                return $building;
            case 3:
                $community_id = request()->post('community_id');
                $group = request()->post('group');
                $building = request()->post('building');
                $unit = array_unique((new roominfoService())->unitList($community_id,$group,$building));
                sort($unit);
                return $unit;
            case 4:
                $community_id = request()->post('community_id');
                $group = request()->post('group');
                $building = request()->post('building');
                $unit = request()->post('unit');
                $room = array_unique((new roominfoService())->roomList($community_id,$group,$building,$unit));
                sort($room);
                return $room;
            case 5:
                $com = $this->pidTokenId();
                $whe['community_id'] = array('in',$com['community_id']);//所有小区ID
                $community_name = request()->post('community_name');
                return Db::name('community')
                        ->where('community_name','like','%'.$community_name.'%')
                        ->where($whe)
                        ->field('community_id,community_name')
                        ->select()->toArray();
            default:
                return json(['info' => '查询错误']);
        }
    }

    //获取该小区费用类型
    public function getCosttype(){
        $community_id=request()->param("community_id");
        $communityinfo=Db::name('community')->where('community_id',$community_id)->field("property_id")->find();
        $costtype=Db::table("costtype")->where("property_id",$communityinfo["property_id"])->column('type');
        return $costtype;
    }
   
    //显示小区房屋信息
    public function roominfoList(){
        //查询小区信息
        $com = $this->pidTokenId();
        //$whe['community_id'] = array('in',$com['community_id']);//所有小区ID
        $whe[] = ['community_id','in',$com['community_id']];//所有小区ID
        $communitylist = (new roominfoService())->communityList($whe);
        $community_id = $com['community_id'];
        View::assign('communitylist',$communitylist);

		$str="[";
		foreach ($communitylist as $key => $value) {
			$str=$str."'".$value["community_name"]."',";
		}
		$str=$str."]";
		
		View::assign("str",$str);
        //查询
        $data = request()->get();
        if (!empty($data['community_id'])){
            $groups = array_unique((new roominfoService())->groupList($data['community_id']));
            View::assign('groups', array_values($groups));
                if (empty($data['group'])) {
                    $data['group'] = '';
                }       
                $buildings = array_unique((new roominfoService())->buildingList($data['community_id'],$data['group']));
                sort($buildings);
                View::assign('buildings',$buildings);
                if (!empty($data['building'])) {
                    $units = array_unique((new roominfoService())->unitList($data['community_id'], $data['group'],$data['building']));
                    sort($units);
                    View::assign('units',$units);
                    if(!empty($data['unit'])){
                        $rooms = array_unique((new roominfoService())->roomList($data['community_id'], $data['group'],$data['building'],$data['unit']));
                        sort($rooms);
                        View::assign('rooms',$rooms);
                    }
                }
        }

        if (!empty($data)){
            if(!empty($data['community_id'])){
                $where['community_id'] = $data['community_id'];//小区名称
            }else{
                $where['community_id'] = "";
            }
            if(!empty($data['out_room_id'])){
                $where['out_room_id'] = $data['out_room_id'];//房屋编号
            }else{
                $where['out_room_id'] = "";
            }
            if(!empty($data['group'])){
                $where['group'] = $data['group'];//组团
            }else{
                $where['group'] = "";
            }
            if(!empty($data['building'])){
                $where['building'] = $data['building'];//楼栋
            }else{
                $where['building'] = "";
            }
            if(!empty($data['address'])){
                $where['address'] = array("like","%".$data['address']."%");//楼栋
            }else{
                $where['address'] = "";
            }
            if(!empty($data['unit'])){
                $where['unit'] = $data['unit'];//单元
            }else{
                $where['unit'] = "";
            }
            if(!empty($data['room'])){
                $where['room'] = $data['room'];//房号
            }else{
                $where['room'] = "";
            }
            if(!empty($data['owner_name'])){
                $where['owner_name'] = $data['owner_name'];//姓名
            }else{
                $where['owner_name'] = "";
            }
            if(!empty($data['owner_phone'])){
                $where['owner_phone'] = $data['owner_phone'];//电话
            }else{
                $where['owner_phone'] = "";
            }
            if(!empty($data['status'])){
                $where['status'] = $data['status'];//状态
            }else{
                $where['status'] = "";
            }
            View::assign('where',$where);   
            $where = array_filter($where);
        }else{
            $where = null;
        }
        $export = $where;
        $export = json_encode($export);
        $export = str_replace("\"","|",$export);
        View::assign('export',$export);
        $page = request()->has('page') ? request()->get('page') : 1;
        //查询房屋条数
       
        $number =(new roominfoService())->roomWhereNumber($community_id,$where);
        View::assign('number',$number);
        //查询房屋信息
        
        $roomlist = (new roominfoService())->roomWhereList($community_id,$page,$where);
        
        //判断是否有数据
        if(!empty($number)){
            foreach($roomlist as $room){
                
                //根据小区编号查询小区名称
                $room['community_id'] = (new roominfoService())->communityName($room['community_id']);
                //数据从新存入数组
                $list[] = $room;
                View::assign('list',$list);
            }
        }else{
            View::assign('list',$roomlist);
        }
        //View::assign('list',$roomlist);
        View::assign('roomlist',$roomlist);
       
        foreach ($data as $k => $v) {
            View::assign($k, $v);
        }
        $proStr='[';
        
        
        foreach($communitylist as $value){
            $proStr=$proStr.'{';
                
                $proStr=$proStr.'"NAME":"'.$value["community_name"].'",';
                $proStr=$proStr.'"ITEMS":';
                    $proStr=$proStr.'[';
                    
                    $group=Db::table("roominfo")->where("community_id",$value["community_id"])->distinct("group")->field("group")->select()->toArray();
                    foreach($group as $gro){
                        
                        $proStr=$proStr.'{';
                            $proStr=$proStr.'"NAME":"'.$gro["group"].'"';
                        $proStr=$proStr.'},';
                    }
                    $proStr=substr($proStr,0,strlen($proStr)-1);
                    $proStr=$proStr.']';
            $proStr=$proStr.'},';
        }
        $proStr=substr($proStr,0,strlen($proStr)-1);
        $proStr=$proStr.']';
        
        //$proStr='[{"ID":"1","NAME":"北京市","ITEMS":[{"ID":"1","NAME":"北京市","ITEMS":[{"ID":"1","NAME":"东城区"}]}]}]';
        View::assign("proStr",$proStr);
        return View::fetch('roominfo_list');
    }

   

    //添加小区房屋信息
    public function roominfoAdd(){
        //查询小区信息
        $com = $this->pidTokenId();
        $where['community_id'] = array('in',$com['community_id']);
        $communitylist = (new roominfoService())->communityList($where);
        View::assign('communitylist',$communitylist);

        if(request()->isPost()){
            //获取表单数据
            $data = request()->post();
            //房屋完整门牌
            $data['address'] = $data['group']."-".$data['building']."-".$data['unit']."-".$data['room'];

            //判断房屋是否重复
            $info = (new roominfoService())->roominfoName($data['community_id'],$data['address']);
            if($info){
                $this->error('房屋已存在');
            }
            $data['time'] = date('Y-m-d H:i:s',time());//添加时间
            $data['batch_id'] = date('YmdHis', time()).\util\Tool::getRandomStr(6);//请求批次号
            $data['out_room_id'] = date('YmdHis', time()).\util\Tool::getRandomStr(8);//支付宝房屋编号
            $data['status'] = 2;//未同步
            if(empty($data["group"])){
                $community=Db::table("community")->where("community_id",$data["community_id"])->find();
               
                $data["zz_group"]=$community["community_name"];
            }else{
                $data["zz_group"]=$data['group'];
            }
            //将数据插入数据库
            $result = (new roominfoService())->roominfoAdd($data);
            //判断数据是否插入成功
            if($result){
                return "添加房屋成功";
                $this->success('添加房屋成功',url('roominfoAdd'));
            }else{
                //return "添加房屋失败";
                $this->error('添加房屋失败',url('roominfoAdd'));
            }
        }else{
            return View::fetch('roominfo_add');
        }
    }

    //修改小区房屋信息
    public function roominfoEdit(){
        //查询小区信息
        $com = $this->pidTokenId();
        $where['community_id'] = array('in',$com['community_id']);
        $communitylist = (new roominfoService())->communityList($where);
        View::assign('communitylist',$communitylist);
        
        if(request()->isGet()){
            if(!request()->has('id') || empty(request()->param('id'))){
                $this->error('房屋ID错误');
            }
            $id = request()->param('id');
            //查询房屋数据
            $info = (new roominfoService())->roominfoIdList($id);
            $info["community_name"]=(new roominfoService())->communityName($info['community_id']);
            View::assign('info',$info);
            return View::fetch('roominfo_edit');
        }else{
            //获取表单数据
            $data = request()->post();
            $data = array_filter($data);
            //var_dump($data);die;
            $billinfo=Db::table("bill")->where('out_room_id',$data["out_room_id"])->where("status","WAIT_PAYMENT")->select()->toArray();
            /*if(!empty($billinfo)){
                 $this->error('请先删除该房屋下未付款的账单再修改房屋');
            }*/
            //房屋完整门牌
            /*if(empty($data['group'])){
                $data['address'] = $data['building'].$data['unit'].$data['room'];
            }else{
                $data['address'] = $data['group'].$data['building'].$data['unit'].$data['room'];
            }*/
            //将修改的数据插入数据库
            $result = (new roominfoService())->roominfoEdit($data);
            //判断数据是否插入成功
            if($result){
                return "修改房屋信息成功";
                $this->success('修改房屋信息成功',url('roominfolist'));
            }else{
                $this->error('修改房屋信息失败',url('roominfoEdit'));
            }
        }
    }
    public function roominfoDelId(){
        $id=request()->get("id");
        $result = (new roominfoService())->deleteRoomInfo($id);

        if($result){
            $this->success("删除房屋成功");
        }else{
            $this->error("删除房屋失败");
        }

    }
    
    public function roominfoDel(){
       
        $id = explode(',',request()->param('id'));
        $roomlist = (new roominfoService())->checkRoomInfo($id);
        if (count($roomlist) != count($id)) {
            return json(['error' => '房屋信息不存在']);
        }
        //查询房屋同步的状态
        $status=Db::table("roominfo")->where("id","in",$id)->distinct("status")->field("status")->select()->toArray();
        if(count($status)!="1"){
            return json(['error' => '请分别删除已同步未同步的房屋']);
        }
        $roomlist1=$roomlist;
        foreach($roomlist as $inf){
            //查询改房屋下是否有账单，如果有账单则需要先删除账单
            $billinfo=Db::table("bill")->where("out_room_id",$inf["out_room_id"])->find();
            if(!empty($billinfo)){
                return  json(['error' => '房屋删除失败,请先删除该房屋下的账单']); 
            }
        }
         //未同步的房屋删除
        foreach($roomlist as $inf){
            $result = (new roominfoService())->deleteRoomInfo($inf['id']);
            if(empty($result)){
                return json(['error' => '房屋删除失败']); 
            }
        }
        return json(['info' => '删除成功']);
        if($status[0]["status"]=="1"){
            //已同步的房屋删除
            
            //查询房屋是否属于同一小区
            $community=Db::table("roominfo")->where("id","in",$id)->distinct("community_id")->field("community_id")->select()->toArray();
            if(count($community)!="1"){
                return json(['error' => '房屋不是同一小区无法批量删除']);
            }
            $community_id=$community[0]["community_id"];
            $batch_id=date('YmdHis', time()).\util\Tool::getRandomStr(6);//请求批次号;
            $token = (new roominfoService())->communityToken($community_id);
            if($token){
                $api = new apiService(config('app')['delroom'], 'https://openapi.alipay.com/gateway.do');
                $res = $api->delRoom2(json_encode(['batch_id' => $batch_id, 'community_id' =>  $community_id, 'token' => $token]),json_encode($roomlist));
                if (!isset($res['error'])) {
                    foreach($roomlist as $inf){
                        $result = (new roominfoService())->deleteRoomInfo($inf['id']);
                    }
                    return json(['info' => '删除成功']);
                }else{
                    return json(['error' => $res['error']]);
                }
            }else{
                return json(['error' => 'token获取失败']);
            }
            
        }else if($status[0]["status"]=="2"){
            //未同步的房屋删除
            foreach($roomlist as $inf){
                $result = (new roominfoService())->deleteRoomInfo($inf['id']);
                if(empty($result)){
                    return json(['error' => '房屋删除失败']); 
                }
            }
            return json(['info' => '删除成功']);
        }else{
            return json(['error' => '房屋删除失败']);
        }
        
        
        //查询小区是否属于同一批次
        /*$batch=Db::table("roominfo")->where("id","in",$id)->distinct("batch_id")->field("batch_id")->select()->toArray();
        if(count($batch)!="1"){
            return json(['error' => '房屋不是同一批次无法批量同步']);
        }*/
       
    }
    //删除房屋信息
    public function roominfoDel2(){
        //判断是否存在该数据
        $id = explode(',',request()->param('id'));
        $info = (new roominfoService())->checkRoomInfo($id);
        if (count($info) != count($id)) {
            return json(['error' => '房屋信息不完整']);
        }
        $api = new apiService(config('app')['delroom'], 'https://openapi.alipay.com/gateway.do');
        foreach($info as $inf){
            //查询改房屋下是否有账单，如果有账单则需要先删除账单
            $billinfo=Db::table("bill")->where("out_room_id",$inf["out_room_id"])->find();
            if(!empty($billinfo)){
                return  json(['error' => '房屋删除失败,请先删除该房屋下的账单']); 
            }
            if($inf["status"]=="1"){
                $inf= Db::table("roominfo")->where("out_room_id",$inf["out_room_id"])->find();
                $token = (new communityService())->communityinfoToken($inf['community_id']);
                $res = $api->delRoom(json_encode(['community_id' =>  $inf['community_id'], 'batch_id' => $inf['batch_id'],'out_room_id'=>$inf['out_room_id'], 'token' => $token]));
                if (!isset($res['error'])) {
                    $result = (new roominfoService())->deleteRoomInfo($inf['id']);
                    if(empty($result)){
                        return json(['error' => '房屋删除失败']);
                    } 
                }else{
                    return json(['error' => $res['error']]);
                }
            }else{
                $result = (new roominfoService())->deleteRoomInfo($inf['id']);
                if(empty($result)){
                    return json(['error' => '房屋删除失败']); 
                }
            }
            
        }
        return json(['info' => '删除成功']);
    }
    
    //通过Excel批量添加房屋信息 
    public function roomExcel(){
        if(request()->isPOST()){
            //上传excel文件
            $file = request()->file('myfile');
            //移到/public/excel/下
            $info = $file->move(ROOT_PATH.'public'.DS.'excel');
            //上传文件成功
            if ($info) {
                //引入PHPExcel类
                vendor('PHPExcel.PHPExcel.Reader.Excel2007');
                //获取上传后的文件名
                $fileName = $info->getSaveName();
                //文件路径
                $filePath = dir(getcwd())->path.'/excel/'.$fileName;
                //判断文件格式，实例化相应的PHPExcel类，读取excel文件
                $extension = strtolower( pathinfo($fileName, PATHINFO_EXTENSION));
                if ($extension =='xlsx' || $extension =='xls') {
                    $objReader = new \PHPExcel_Reader_Excel2007();
                    $objPHPExcel = $objReader ->load($filePath);
                } else if ($extension=='csv') {
                    $objReader = new \PHPExcel_Reader_CSV();
                    //默认输入字符集
                    $objReader->setInputEncoding('GBK');
                    //默认的分隔符
                    $objReader->setDelimiter(',');
                    //载入文件
                    $objPHPExcel = $objReader ->load($filePath);
                }else{
                    $this->success('文件格式错误',url('billExcel'));
                }  
                //读取excel文件中的第一个工作表
                $sheet = $objPHPExcel->getSheet(0);
                $allRow = $sheet->getHighestRow();  //取得总行数
                //$allColumn = $sheet->getHighestColumn();  //取得总列数
                //从第三行开始插入，第一行是列名
                for ($j=2; $j <= $allRow; $j++) {
                    $communityName = $objPHPExcel->getActiveSheet()->getCell("A".$j)->getValue();//小区名称
                    if(isset($communityName)){
                        $communityList = (new roominfoService())->communityNameId($communityName);
                        if(isset($communityList)){
                            $data['community_id'] = $communityList['community_id'];  
                        }else{
                            $data['community_id'] = '';
                        }  
                    }else{
                        $data['community_id'] = '';
                    }
                    $data['group'] = $objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();//组团
                    $data['building'] = $objPHPExcel->getActiveSheet()->getCell("C".$j)->getValue();//楼栋
                    $data['unit'] = $objPHPExcel->getActiveSheet()->getCell("D".$j)->getValue();//单元
                    $data['room'] = $objPHPExcel->getActiveSheet()->getCell("E".$j)->getValue();//房号
                    $data['address'] = $data['group']."-".$data['building']."-".$data['unit']."-".$data['room'];
                    $data['owner_name'] = $objPHPExcel->getActiveSheet()->getCell("F".$j)->getValue();//业主姓名
                    $data['owner_phone'] = $objPHPExcel->getActiveSheet()->getCell("G".$j)->getValue();//业主电话
                    $data['area'] = $objPHPExcel->getActiveSheet()->getCell("H".$j)->getValue();//面积
                    $data['price'] = $objPHPExcel->getActiveSheet()->getCell("I".$j)->getValue();//单价
                    $data['cost'] = $objPHPExcel->getActiveSheet()->getCell("J".$j)->getValue();//费用
                    $data['status'] = '2';//同步状态，默认未同步
                    
                    $data['out_room_id'] = date('YmdHis', time()).\util\Tool::getRandomStr(8);//支付宝房屋编号
                    $data['time'] = date('Y-m-d H:i:s',time());//添加时间

                    $data = array_filter($data);
                    $number = count($data);
                    $numbers = 14;
                    if( $number >= $numbers){
                        //判断房屋是否重复
                        $comaddress = (new roominfoService())->roomComAddress($data['community_id'],$data['address']);
                        if($comaddress){
                            echo "第".$j."行房间号重复，导入失败！<br/>";
                        }else{
                            
                            $last_id = (new roominfoService())->roomExcelAdd($data); 
                            //判断数据是否插入成功
                            if ($last_id) {
                                echo "第".$j."行导入成功，users表第:".$last_id."条！<br/>";
                            }else{
                                echo "第".$j."行导入失败！<br/>";
                            } 
                        }
                    }else{
                        echo "第".$j."行数据不完整，导入失败！<br/>";
                    }
                }
            }else{
                $this->success('上传文件失败',url('roomExcel'));
            }
        }else{
            return View::fetch('room_excel');
        }
    }

    //导出房屋到Excel
    public function roomExportExcel(){
        //获取账单数据
        $id = request()->param('id');
        $export = request()->param('export');
        $export = str_replace("|","\"",$export);
        if(!empty($id)){
            $id = explode(',',request()->param('id'));
            $roomlist = (new roominfoService())->checkRoomInfo($id);
            if(count($roomlist) != count($id)){
                return json(['error' => '房屋信息不完整']);
            }
        }else{
            //查询小区信息
            $com = $this->pidTokenId();
            $whe['community_id'] = array('in',$com['community_id']);
            $communitylist = (new roominfoService())->communityList($whe);
            $community_id = $com['community_id'];
            $where = json_decode($export,true);
            
            $roomlist = (new roominfoService())->roomWhere($community_id,$where);
            if(empty($roomlist)){
                return json(['error' => '没有账单数据']);
            }
        }
        //设置表头
        //引入PHPExcel类
        vendor('PHPExcel.PHPExcel.Reader.Excel2007');
        $objPHPExcel = new \PHPExcel();
        //设置表头
        $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue('A1', '支付宝房屋ID')
        ->setCellValue('B1', '小区名称')
        ->setCellValue('C1', '组团')
        ->setCellValue('D1', '楼栋')
        ->setCellValue('E1', '单元')
        ->setCellValue('F1', '房号')
        ->setCellValue('G1', '完整门牌号')
        ->setCellValue('H1', '业主姓名')
        ->setCellValue('I1', '业主电话')
        ->setCellValue('J1', '状态');

        $count = count($roomlist);  //计算有多少条数据
        for ($i=2; $i <= $count+1; $i++) {
            //根据小区ID查询小区名称
            $commId = $roomlist[$i-2]["community_id"];
            $communityName = (new roominfoService())->communityIdName($commId);
            $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $roomlist[$i-2]["out_room_id"]);
            $objPHPExcel->getActiveSheet()->setCellValue('B' . $i, $communityName['community_name']);
            $objPHPExcel->getActiveSheet()->setCellValue('C' . $i, $roomlist[$i-2]["group"]);
            $objPHPExcel->getActiveSheet()->setCellValue('D' . $i, $roomlist[$i-2]["building"]);
            $objPHPExcel->getActiveSheet()->setCellValue('E' . $i, $roomlist[$i-2]["unit"]);
            $objPHPExcel->getActiveSheet()->setCellValue('F' . $i, $roomlist[$i-2]["room"]);
            $objPHPExcel->getActiveSheet()->setCellValue('G' . $i, $roomlist[$i-2]["address"]);
            $objPHPExcel->getActiveSheet()->setCellValue('H' . $i, $roomlist[$i-2]["owner_name"]);
            $objPHPExcel->getActiveSheet()->setCellValue('I' . $i, $roomlist[$i-2]["owner_phone"]);
            $status="";
            if($roomlist[$i-2]["status"] == 1){
                $status = '已同步';
            }elseif($roomlist[$i-2]["status"] == 2){
                $status = '未同步';
            }
            $objPHPExcel->getActiveSheet()->setCellValue('J' . $i, $status);
        }
        $objPHPExcel->getActiveSheet()->setTitle('房屋信息');      //设置sheet的名称
        $objPHPExcel->setActiveSheetIndex(0);                   //设置sheet的起始位置
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');   //通过PHPExcel_IOFactory的写函数将上面数据写出来
        $PHPWriter = \PHPExcel_IOFactory::createWriter( $objPHPExcel,"Excel2007");
        header('Content-Disposition: attachment;filename="房屋信息.xls"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件
    }
    
    //同步房屋到支付宝
    public function roomUpload(){
        //判断是否存在该数据
        $uid=request()->param('id');
        $id = explode(',',request()->param('id'));
        $roomlist = (new roominfoService())->checkRoomInfo($id);
        if (count($roomlist) != count($id)) {
            return json(['error' => '房屋信息不存在']);
        }
        //查询房屋同步的状态
        $status=Db::table("roominfo")->where("id","in",$id)->distinct("status")->field("status")->select()->toArray();
        if(count($status)!="1"){
            return json(['error' => '已经同步的房屋无法同步无法批量同步']);
        }
        if($status[0]["status"]=="1"){
            return json(['error' => '已经同步的房屋无法同步无法批量同步']);
        }
        
        //查询房屋是否属于同一小区
        $community=Db::table("roominfo")->where("id","in",$id)->distinct("community_id")->field("community_id")->select()->toArray();
        if(count($community)!="1"){
            return json(['error' => '房屋不是同一小区无法批量同步']);
        }
        //查询小区是否属于同一批次
        /*$batch=Db::table("roominfo")->where("id","in",$id)->distinct("batch_id")->field("batch_id")->select()->toArray();
        if(count($batch)!="1"){
            return json(['error' => '房屋不是同一批次无法批量同步']);
        }*/
        $community_id=$community[0]["community_id"];
        $batch_id=date('YmdHis', time()).\util\Tool::getRandomStr(6);//请求批次号;
        
        //Log::write($batch_id,"batch");
        $token = (new roominfoService())->communityToken($community_id);
       // var_dump($roomlist);die;
        //循环将数据存入支付宝
       if($token){
            $api = new apiService(config('app')['addroom'], 'https://openapi.alipay.com/gateway.do');
            $res = $api->addRoom2(json_encode(['batch_id' => $batch_id, 'community_id' =>  $community_id, 'token' => $token]),json_encode($roomlist));
            //判断是否存入支付宝
            if (!isset($res['error'])) {
                Db::table("roominfo")->where("id","in",$id)->update(["status"=>"1","batch_id"=>$batch_id]);
                return json(['info' => '同步成功']); 
            }else{
                return json(['error' => $res['error']]);
            }
        }else{
            return json(['error' => '房屋信息不存在']); 
        }
               
    }
    public function roomUpdate(){

        $id = explode(',',request()->param('id'));
        $res=Db::table("roominfo")->where("id","in",$id)->update(["status"=>"2"]);
        if($res){
            return json(['info' => '更改成功']);
        }else{
            return json(['error' => '更改失败']);
        }

    }
    //查询小区下所有房屋
    public function CommunityRoomList(){
        $community_id = "ARYYP7RQA3301";//支付宝小区编号
        $token = '202007BBb5f8b77753a44991b5e7179ea5df1E83';//token
        $page = '1';//页数，一页500条
        $api = new apiService(config('app')['listroom'],'https://openapi.alipay.com/gateway.do');
        $list = $api->listRoom($community_id,$token,$page);
        $result=$this->object_to_array($list);
        dump($list,true);exit();
    }
    
    public function billquery(){
        $id=request()->get("id");
        $info = (new roominfoService())->roominfoIdList($id);
        if($info["status"]=="2"){
            return "房屋未同步无法查询";
        }
		$info = Db::table("roominfo")->where('out_room_id',$info["out_room_id"])->find();
		
	
		//var_dump($info);
		$token = (new billService())->billinfoToken($info["community_id"]);
		$api = new apiService(config('app')['roombilllist'], 'https://openapi.alipay.com/gateway.do');
		$res = $api->roomBillList(json_encode(['community_id' =>  $info['community_id'], 'out_room_id' => $info['out_room_id'],'batch_id' => "", 'bill_status' => '',  'cost_type' => '' , 'acct_period' => '' , 'release_day' => '' ,'token' => $token]));//WAIT_PAYMENT
	    
	    if(isset($res["success"])){
	        if($res["success"]->code="10000"){
	            if($res["success"]->total_bill_count!="0"){
	                $billlist=$this->object_to_array($res["success"]->bill_result_set);
        		    echo "<pre>";var_dump($billlist);die;
        		    View::assign("list",$billlist);
        		    return View::fetch();
	            }else{
	                return "无未交费账单";
	            }
    		    
    		}else{
    		    return "查询失败";
    		}
	    }else{
	        return "查询失败";
	    }
		

    }
    
    public function object_to_array($obj){
        $_arr = is_object($obj) ? get_object_vars($obj) :$obj;
        foreach($_arr as $key=>$val){
            //if($key !== 'gioouts'){
                $val = (is_array($val) || is_object($val)) ? $this->object_to_array($val):$val;
                $arr[$key] = $val;
           // }
        }
        return $arr;
    }
    
    public function getgroup(){
		$community_id = request()->param('community_id');
        $communityinfo=Db::table("community")->where("community_name",$community_id)->find();
        $community_id=$communityinfo["community_id"];
        $group = (new xcxService())->groupList($community_id);  
        
        sort($group ,SORT_NATURAL|SORT_STRING|SORT_FLAG_CASE);
    
        return $group ;
	}
    
	public function getbuilding(){
		$community_id = request()->param('community_id');
		
        $communityinfo=Db::table("community")->where("community_name",$community_id)->find();
        $community_id=$communityinfo["community_id"];
        $group = request()->param('group');;
        $building = (new xcxService())->buildingList($group,$community_id);
        sort($building,SORT_NATURAL|SORT_STRING|SORT_FLAG_CASE);
        return $building;
	}
	public function getunit(){
		$community_id = request()->param('community_id');
		$communityinfo=Db::table("community")->where("community_name",$community_id)->find();
        $community_id=$communityinfo["community_id"];
        $group = request()->param('group');;
        $building = request()->param('building');
        $unit = (new xcxService())->unitList($building,$group,$community_id);
        Log::write($group,"2343");
        sort($unit,SORT_NATURAL|SORT_STRING|SORT_FLAG_CASE);
        return $unit;
	}
	public function getroom(){
		$community_id = request()->param('community_id');
		$communityinfo=Db::table("community")->where("community_name",$community_id)->find();
        $community_id=$communityinfo["community_id"];
        $group = request()->param('group');;
        $building = request()->param('building');
        $unit = request()->param('unit');
        $room = (new xcxService())->roomList($unit,$building,$group,$community_id);
        sort($room,SORT_NATURAL|SORT_STRING|SORT_FLAG_CASE);
        return $room;
	}
}